<template>
  <div class="app-container">
    <!-- 查询表单区域 -->
    <div style="margin-bottom: 20px; float: left">
      <el-form :inline="true"
               :model="queryParams"
               ref="queryParams"
               label-position="right"
               size="small"
               class="demo-form-inline">

        <el-form-item label="数据库类型：" prop="db_type">
          <el-radio-group v-model="queryParams.db_type">
            <el-radio-button v-for="(item, index) in dbTypeFilters" :key="index" :label="item">{{ item }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="用户类型：" prop="user_type">-->
<!--          <el-radio-group v-model="queryParams.user_type">-->
<!--            <el-radio-button v-for="(item, index) in userTypeFilters" :key="index" :label="item">{{ item }}</el-radio-button>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="queryParams.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="搜索：">
          <el-input v-model="queryParams.search" placeholder="支持多条件搜索" clearable style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter(queryParams)">查询</el-button>
          <el-button @click="resetForm('queryParams')">重置</el-button>
          <el-button type="success" @click="handleAdd" style="margin-left: 20px">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 账户列表表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        v-for="(column, index) in columns"
        :key="index"
        :align="column.align || 'left'"
        :label="column.label"
        :width="column.width"
        :fixed="column.fixed"
      >
        <template slot-scope="scope">
          <!-- 处理时间字段 -->
          <template v-if="['create_time', 'update_time'].includes(column.prop)">
            <span>{{ scope.row[column.prop] }}</span>
          </template>
          <template v-else>
            {{ scope.row[column.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 新增/编辑账户对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%" style="margin-top:-80px">
      <el-form ref="dataForm" :rules="rules" :model="temp" size="small"
               label-position="right" label-width="120px" label-suffix=" :">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据库类型" prop="db_type">
              <el-radio-group v-model="temp.db_type">
                <el-radio-button v-for="(item, index) in dbTypeOptions" :key="index" :label="item" :value="item">{{ item }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="temp.username"/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="temp.password"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="temp.remark"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="user_type">
              <el-radio-group v-model="temp.user_type">
                <el-radio-button v-for="(item, index) in userTypeOptions" :key="index" :label="item" :value="item">{{ item }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="数据库 ID" prop="database_id">
              <el-input v-model.number="temp.database_id"/>
            </el-form-item>
            <el-form-item label="集群 ID" prop="cluster_id">
              <el-input v-model.number="temp.cluster_id"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAccountsList, createAccount, updateAccount, deleteAccount } from '@/api/meta-data';

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      columns: [
        { prop: "id", label: "ID", width: 95, fixed: "left" },
        { prop: "username", label: "用户名", width: 135, fixed: "left" },
        { prop: "password", label: "密码", width: 120 },
        { prop: "user_type", label: "用户类型", width: 100 },
        { prop: "cluster_id", label: "集群 ID", width: 100 },
        { prop: "database_id", label: "数据库 ID", width: 100 },
        { prop: "db_type", label: "数据库类型", width: 100 },
        { prop: "remark", label: "备注", width: 200 },
        { prop: "create_time", label: "创建时间", width: 200 },
        { prop: "update_time", label: "更新时间", width: 200 },
      ],
      queryParams: {
        search: '',
        username: '',
        db_type: 'ALL',
        // user_type: 'ALL',
      },
      dbTypeFilters: ['ALL', 'MySQL', 'PostgreSQL'],
      dbTypeOptions: ['MySQL', 'PostgreSQL'],
      userTypeFilters: ['ALL', 'rw', 'ro'],
      userTypeOptions: ['rw', 'ro'],
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        create: '新增',
        edit: '编辑'
      },
      temp: {
        id: null,
        username: '',
        password: '',
        user_type: 'rw',
        cluster_id: null,
        database_id: null,
        db_type: 'MySQL',
        remark: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        user_type: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
        cluster_id: [
          { required: true, message: '请输入集群 ID', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        database_id: [
          { required: true, message: '请输入数据库 ID', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        db_type: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
        remark: [{ required: false, message: '', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取账户列表数据
    fetchData() {
      this.listLoading = true;
      const params = {
        page: this.currentPage,
        page_size: this.pageSize,
        ...this.queryParams
      };
      if (this.queryParams.db_type === 'ALL') {
        params.db_type = null;
      }
      // if (this.queryParams.user_type === 'ALL') {
      //   params.user_type = null;
      // }
      getAccountsList(params).then(response => {
        this.list = response.data.records;
        this.total = response.data.count;
        this.listLoading = false;
      });
    },
    // 处理查询过滤
    handleFilter(params) {
      this.currentPage = 1;
      this.fetchData();
    },
    // 重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.queryParams = {
        search: '',
        username: '',
        db_type: 'ALL',
        // user_type: 'ALL',
      };
      this.currentPage = 1;
      this.fetchData();
    },
    // 处理每页显示数量变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    // 处理当前页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    // 处理删除账户
    handleDelete(id) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAccount(id).then(() => {
          this.fetchData();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 处理编辑账户
    handleEdit(row) {
      this.dialogStatus = 'edit';
      this.temp = { ...row };
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    // 处理新增账户
    handleAdd() {
      this.dialogStatus = 'create';
      this.temp = {
        id: null,
        username: '',
        password: '',
        user_type: 'rw',
        cluster_id: null,
        database_id: null,
        db_type: 'MySQL',
        remark: ''
      };
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    // 创建账户
    createData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          createAccount(this.temp).then(() => {
            this.dialogFormVisible = false;
            this.fetchData();
            this.$message({
              type: 'success',
              message: '新增成功'
            });
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '新增失败'
            });
          });
        } else {
          return false;
        }
      });
    },
    // 更新账户
    updateData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          updateAccount(this.temp.id, this.temp).then(() => {
            this.dialogFormVisible = false;
            this.fetchData();
            this.$message({
              type: 'success',
              message: '更新成功'
            });
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '更新失败'
            });
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
/* 可在此添加自定义样式 */
</style>
